package com.wap.framework.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wap.framework.util.Constants;

public class SecurityFilter implements Filter {

	protected FilterConfig filterConfig;

	private String redirectURL = null;

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;

		HttpSession session = request.getSession(false);	
		if (session == null) {//session time out
			sendRedirect(response);
		} else if (session.getAttribute(Constants.ADMIN_TOKEN) == null) { //session user is null
			sendRedirect(response);
		} else {//normal case
			filterChain.doFilter(request, response);
		}
	}

	private void sendRedirect(HttpServletResponse response) {
		PrintWriter out;
		try {
			out = response.getWriter();
			out.println("<script type='text/javascript'>");
			out.println("window.parent.location = '" + redirectURL + "';");
			out.println("</script>");
			out.close();
		} catch (IOException e) {			
			e.printStackTrace();
		}		
	}
	
	public void init(FilterConfig config) throws ServletException {
		String initParameter = config.getInitParameter("contextPath");
		redirectURL = initParameter + "/login.jsp";
	}
}
